<template>
  <div>
    <el-row>
      <el-progress
        type="circle"
        :percentage="curpercent"
        :format="format"
      ></el-progress>
    </el-row>
    <el-row>
      <el-tooltip placement="top-start" content="播放按钮">
        <el-button
          @click="play()"
          type="primary"
          icon="el-icon-video-play"
          circle
        ></el-button>
      </el-tooltip>
      <el-tooltip placement="top-start" content="暂停按钮">
        <el-button
          @click="vpause"
          type="primary"
          icon="el-icon-video-pause"
          circle
        ></el-button>
      </el-tooltip>
      <el-tooltip placement="top-start" content="下一首">
        <el-button
          @click="playnext"
          type="primary"
          icon="el-icon-caret-right"
          circle
        ></el-button>
      </el-tooltip>
      <el-tooltip content="从文件中添加音乐" placement="top-start">
        <el-button @click="addMusic" type="primary">添加音乐</el-button>
      </el-tooltip>
      <el-tooltip content="清空当前播放列表" placement="top-start">
        <el-button @click="clear" type="primary">清空数据</el-button>
      </el-tooltip>
      <div type="primary" id="playlistcontrol">
        <img
          :src="this.randimg"
          style="width: 15px"
          v-show="this.playerMode == 2"
          @click="changeMode(1)"
        />
        <img
          :src="this.sequenceimg"
          style="width: 15px"
          v-show="this.playerMode == 1"
          @click="changeMode(2)"
        />
      </div>
    </el-row>
    <el-row>
      <c-progress
        class="c-progress"
        :percent="curpercent"
        :show-per-text="false"
        :width="480"
        @percentChange="changeCurTime"
        :cur-time="currenttime"
        :total-time="duration"
      />
    </el-row>

    <el-table
      ref="singleTable"
      :data="musicList"
      @row-click="handleRowChange"
      highlight-current-row
      :row-class-name="crowIndex"
    >
      <el-table-column prop="name" label="名称" width="180"> </el-table-column>
      <el-table-column prop="path" label="路径" width="180"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
/* eslint-disable */

import CProgress from "../components/CProgress";
const fs = require('fs')
import {ipcRenderer} from 'electron'
import DB from "@/utils/db";
import path from "path";


let audio = new Audio()  //音频对象
let audioCtx = new AudioContext()   //音频管理上下文对象
let source = audioCtx.createMediaElementSource(audio) //音乐源
let analyser = audioCtx.createAnalyser() //
source.connect(analyser)
analyser.connect(audioCtx.destination)
let dataArray = new Uint8Array(analyser.frequencyBinCount);

/*
* 根据路径读取文件并转为blob对象
* */
function getlocalobj(path){
    const buf = fs.readFileSync(path)
    const uint8Buffer = Uint8Array.from(buf)
    const blob = new Blob([uint8Buffer])
    //   console.log(blob)
    return window.URL.createObjectURL(blob)
}


/*
*
* 改变audio对象的src
* */
function changeMusic(path) {
    audio.src = getlocalobj(path)
}






ipcRenderer.on('selected-file', (event, pathList) => {
    if (Array.isArray(pathList)) {
        pathList.forEach(
            item=>{
                if(!DB.getExistPath().includes(item)){
                    DB.insert('musicList',{
                        name:path.basename(item),
                        path:item
                    })
                }
            }
    )
    }
    getMusicList()
})
audio.onended=function () {
    playnext()
}

export default {
  name: "MusicPlayer",
    components: {
        CProgress,
    },
    data(){
      return{
          musicList:[
          ],
          currenttime:1,
          duration: 200,
          timer:'',
          playerMode:1,
          pre:0,
          currentRowIndex: 0,
          randimg: require('@/assets/22_随机播放.svg'),
          sequenceimg: require('@/assets/顺序循环.svg')
      }
    },
    methods:{
        getlocalobj(path){
           const buf = fs.readFileSync(path)
            const uint8Buffer = Uint8Array.from(buf)
            const blob = new Blob([uint8Buffer])
         //   console.log(blob)
            return window.URL.createObjectURL(blob)
        },
        changeCurTime(per){
            audio.currentTime = this.duration*per/100
        },
        getCurTime(){
            this.currenttime = audio.currentTime;
            this.duration = audio.duration
      //      analyser.getByteTimeDomainData(dataArray)
        },
        getMusicList(){
            const list = DB.get("musicList");
            this.musicList = list;
            console.log(this.musicList)
        },
        addMusic(){
            ipcRenderer.send('open-music-file','ping')
        },
        clear(){
            DB.rmDB('musicList')
            audio.pause()
            this.getMusicList()
        },
        play(path){
            if(path){
                changeMusic(path)
            }
            audio.play()
        //    console.log(dataArray)
        },
        handleDelete(index,row){
            audio.pause()
            DB.removeById('musicList',row.id)
            this.getMusicList()
        },
        handleRowChange(row,column){
            this.$refs.singleTable.setCurrentRow(row);
            this.currentRowIndex = row.row_index
            this.play(row.path)
        },
        playpre(){
            this.play(this.musicList[this.pre].path)
        },
        playnext(){
            if(this.playerMode==1){
                // 顺序播放
                this.pre = this.currentRowIndex //播放时记录上一首歌曲
                this.currentRowIndex+=1
                this.currentRowIndex=this.currentRowIndex%this.musicList.length
                this.$refs.singleTable.setCurrentRow(this.musicList[this.currentRowIndex]);
                if(!this.musicList[this.currentRowIndex])return;
            }
            else if(this.playerMode==2){
                // 随机播放
                this.pre = this.currentRowIndex //播放时记录上一首歌曲
                this.currentRowIndex = Math.floor(Math.random()*100%this.musicList.length)
                this.$refs.singleTable.setCurrentRow(this.musicList[this.currentRowIndex]);
                this.play(this.musicList[this.currentRowIndex].path)
            }
            else if(this.playerMode==3){
                // 单曲循环
                this.pre = this.currentRowIndex //播放时记录上一首歌曲

            }

        },
        crowIndex({row,rowIndex}){
            row.row_index = rowIndex
        },
        format(percentage){
            let tmp = this.musicList[this.currentRowIndex];
            if(!tmp)return;
            return tmp.name;
        },
        vpause(){
            audio.pause()
        },
        changeMode(number){
            this.playerMode=number
        }

    },
    mounted() {
        window.getMusicList = this.getMusicList //让外部调用vue方法
        window.playnext = this.playnext
        this.timer=setInterval(this.getCurTime,1000/30)
        },
    computed:{
        curpercent(){
            if(!this.duration)return;
            return (this.currenttime/this.duration)*100
        },
    },
    beforeDestroy() {
      clearInterval(this.timer)
    },
    created() {
        ipcRenderer.invoke("getDataPath").then((storePath) => {
            DB.initDB(storePath);
            this.getMusicList();
        });
    }


}

</script>

<style lang="scss">
table{
  border-color: transparent;
}
.el-row{
  text-align: center;
}
.el-progress__text{
  color: white;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
#playlistcontrol{
  padding: 8px;
  vertical-align: middle;
  display: inline-flex;
  justify-content: center;
  align-items: center;
line-height: 1;
white-space: nowrap;
cursor: pointer;
background: #FFF;
border: 1px solid #DCDFE6;
-webkit-appearance: none;
text-align: center;
box-sizing: border-box;
outline: 0;
margin: 0;
transition: .1s;
font-weight: 500;
color: #FFF;
background-color: #409EFF;
border-color: #409EFF;
margin-left: 10px;
width: 32px;
height: 32px;
border-radius: 50%;
}

    .el-table{
        position: relative;
        box-sizing: border-box;
        flex: 1;
        width: 100%;
        max-width: 100%;
        font-size: 14px;
        color: #606266;
        background: transparent;
        *{
          background: transparent!important;
          color: white;
        }
    }
    .el-progress__text{
      background-image: url("~@/assets/音乐.png");
    }
    .c-progress span{
      color :white
    }
</style>
